import 'dart:async';

class CompleterUtil {
  CompleterUtil() {
    _completer = Completer<dynamic>();
  }

  late Completer<dynamic> _completer;

  /// When cancelled, this future will be resolved.
  Future<dynamic> get whenCompleter => _completer.future;

  void complete([dynamic message]) {
    if (!_completer.isCompleted) {
      _completer.complete(message);
    }
  }

  void error([dynamic error]) {
    if (!_completer.isCompleted) {
      _completer.completeError(error);
    }
  }
}

/*
 test() async {
    CompleterUtil c = new CompleterUtil();
    for (var i = 0; i < 1000; i++) {
      if (i == 900 && c.isCompleted == false) {
        c.complete('error in $i');
      }
      if (i == 800 && c.isCompleted == false) {
        c.error('complete in $i');
      }
    }

    try {
      String res = await c.future;
      print(res); //得到complete传入的返回值 'complete in 800'
    } catch (e) {
      print(e);//捕获completeError返回的错误
    }
  }
 */
